﻿using QuickRunCore.Helper;
using QuickRunCore.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace QuickRunCore
{
    public partial class FrmSetup : Form
    {
        /// <summary>
        /// 系统配置信息
        /// </summary>
        ConfigModel Config;

        /// <summary>
        /// 当前运行窗体信息
        /// </summary>
        private static List<WindowInfo> _WindowsInfoList = null;

        private static string _HideAllHotKey = "";

        private static bool _IsAllHide = false;

        /// <summary>
        /// 已经被隐藏的窗体
        /// </summary>
        private static List<HideWindowInfo> _HideWindowsInfo = null;


        public FrmSetup()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 初始化当前系统托盘图标信息
        /// </summary>
        public static void InitIcon()
        {
            if (Common.HideIconProcPath == null)
            {
                Common.HideIconProcPath = JsonHelper.GetObjectFromJsonStr<List<string>>(FileHelper.ReadFileInfo(FileHelper.GetProcDir() + @"\HideIcon"));
            }

            WindowIconHide.TrayItemData[] trayItems = WindowIconHide.GetTrayIconList();

            string FilePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            Common.IconProc = trayItems.Select((m, index) => new WinProc
            {
                //唯一ID
                id = index,
                //是否隐藏
                isHide = Common.HideIconProcPath == null ? false : (Common.HideIconProcPath.Contains(m.lpProcImagePath) ? true : false),
                //窗口句柄
                hWnd = m.hWnd.ToString("X").ToUpper(),
                //进程句柄
                hProcess = m.hProcess.ToString("X").ToUpper(),
                //进程ID
                dwProcessID = m.dwProcessID.ToString(),
                idCommand = m.idCommand,
                //进程映象路径
                lpProcImagePath = m.lpProcImagePath,
                //托盘图标提示内容
                lpTrayToolTip = m.lpTrayToolTip,
                //托盘图标
                hIcon = m.hIcon == IntPtr.Zero ? null : (Icon.FromHandle(m.hIcon).Size.Width == 0 ? null : Icon.FromHandle(m.hIcon)),

            }).ToList();

            Common.IconProc = Common.IconProc.FindAll(m => !string.IsNullOrWhiteSpace(m.lpProcImagePath));

            if (Common.IconProc != null)
            {
                Common.IconProc = Common.IconProc.FindAll(m => m.lpProcImagePath != FilePath);
            }

            foreach (WinProc _wp in Common.IconProc)
            {
                if (_wp.isHide)
                {
                    WindowIconHide.HideTrayIcon(_wp.idCommand, false);
                }
                else
                {
                    WindowIconHide.HideTrayIcon(_wp.idCommand, true);
                }
            }
        }

        /// <summary>
        /// 初始化窗体信息
        /// </summary>
        public static void InitWindows()
        {
            _WindowsInfoList = HideWindow.GetAllWindowInfoList(true);

            _WindowsInfoList = _WindowsInfoList.FindAll(m => m.Handle != IntPtr.Zero);


            if (Common.HideWindowConfig == null)
            {
                Common.HideWindowConfig = JsonHelper.GetObjectFromJsonStr<HideWindowConfig>(FileHelper.ReadFileInfo(FileHelper.GetProcDir() + @"\HideWindow"));
            }

            if (Common.HideWindowConfig == null)
            {
                Common.HideWindowConfig = new HideWindowConfig();
            }

            if (Common.HideWindowConfig != null && Common.HideWindowConfig.HideWindowList != null && _WindowsInfoList != null)
            {
                _HideAllHotKey = Common.HideWindowConfig.HideAllHotKey;

                foreach (HideWindowInfo _hwi in Common.HideWindowConfig.HideWindowList)
                {
                    _WindowsInfoList = _WindowsInfoList.FindAll(m => m.ProcessName != _hwi.ProcessName);
                }
            }

        }


        /// <summary>
        /// 快捷键隐藏窗体
        /// </summary>
        /// <param name="key"></param>
        public static void HideWindowFromHotKey(string key)
        {
            return;
            bool _isHide = true;
            if (Common.HideWindowConfig == null)
            {
                Common.HideWindowConfig = JsonHelper.GetObjectFromJsonStr<HideWindowConfig>(FileHelper.ReadFileInfo(FileHelper.GetProcDir() + @"\HideWindow"));
            }

            if (key.IndexOf("LControlKey") == -1 && key.IndexOf(",") > -1)
            {
                List<HideWindowInfo> _hwil = null;
                if (_HideAllHotKey == key)
                {
                    _isHide = !_IsAllHide;
                    _IsAllHide = !_IsAllHide;
                    if (Common.HideWindowConfig.HideWindowList != null)
                    {
                        _hwil = Common.HideWindowConfig.HideWindowList.FindAll(m => !string.IsNullOrWhiteSpace(m.HideHotKey));
                    }
                }
                else if (Common.HideWindowConfig.HideWindowList != null && Common.HideWindowConfig.HideWindowList.Find(m => m.HideHotKey == key) != null)
                {
                    _hwil = Common.HideWindowConfig.HideWindowList.FindAll(m => m.HideHotKey == key);
                    //查找是否已经有已隐藏的窗体，如果有则标记为要显示隐藏的窗体，否则标记为需要隐藏窗体
                    if (_HideWindowsInfo != null)
                    {
                        _isHide = (_HideWindowsInfo.Find(m => m.HideHotKey == key) == null);
                    }
                    if (_HideWindowsInfo == null)
                    {
                        _HideWindowsInfo = new List<HideWindowInfo>();
                    }
                    if (_isHide)
                    {
                        foreach (HideWindowInfo _hwi in _hwil)
                        {
                            _HideWindowsInfo.Add(_hwi);
                        }
                    }
                    else
                    {
                        foreach (HideWindowInfo _hwi in _hwil)
                        {
                            _HideWindowsInfo.Remove(_hwi);
                        }
                    }

                }

                if (_hwil != null && _hwil.Count > 0)
                {
                    _WindowsInfoList = HideWindow.GetAllWindowInfoList(_isHide);
                    foreach (HideWindowInfo _hwi in _hwil)
                    {
                        foreach (WindowInfo _wi in _WindowsInfoList)
                        {

                            if (_wi.ProcessName == _hwi.ProcessName)
                            {
                                HideWindow.HideWindowFromHandle(_wi.Handle, _isHide);
                                //break;
                            }
                        }
                    }
                }


            }
        }

        /// <summary>
        /// 键盘快捷键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void HotKeyUp(object sender, MyEventArgs e)
        {
            if (txtAllHideHotKey.Focused)
            {
                string _key = Convert.ToString(e.Tag);
                if (_key == "Back")
                {
                    txtAllHideHotKey.Text = "";
                }
                if (_key.IndexOf("LControlKey") == -1 && _key.IndexOf(",") > -1)
                {
                    txtAllHideHotKey.Text = _key;
                }
            }
            else if (txtHideHotKey.Focused)
            {
                if (gridWindows.CurrentRow != null)
                {
                    string _key = Convert.ToString(e.Tag);
                    if (_key == "Back")
                    {
                        txtHideHotKey.Text = "";
                    }
                    if (_key.IndexOf("LControlKey") == -1 && _key.IndexOf(",") > -1)
                    {
                        txtHideHotKey.Text = _key;
                    }
                }
            }
            //else
            //{
            //    string _key = Convert.ToString(e.Tag);
            //    if (_key == _hideAllHotKey)
            //    {

            //    }
            //    else
            //    {

            //    }
            //}
        }

        /// <summary>
        /// 关闭窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void skinForm1_CloseButtonClick(object sender, EventArgs e)
        {
            Common.HideWindowConfig = null;
            DialogResult = DialogResult.Cancel;
        }

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmSetup_Load(object sender, EventArgs e)
        {
            //显示所有正常图标
            WindowIconHide.HideAllTrayIcon(true);

            InitIcon();

            gridIcon.DataSource = Common.IconProc;

            //则将DataGridView的列自动调整模式设置为显示的列即可， 
            this.gridIcon.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
            //不显示最左侧光标列
            gridIcon.RowHeadersVisible = false;
            //禁止用户改变DataGridView1所有行的行高  
            gridIcon.AllowUserToResizeRows = false;

            gridIcon.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;



            //隐藏窗体
            InitWindows();
            txtAllHideHotKey.Text = _HideAllHotKey;

            gridWindows.DataSource = _WindowsInfoList;

            if (Common.HideWindowConfig.HideWindowList != null)
            {
                gridHideWindow.DataSource = new System.ComponentModel.BindingList<HideWindowInfo>(Common.HideWindowConfig.HideWindowList);
            }


            //不显示最左侧光标列
            gridWindows.RowHeadersVisible = false;
            //禁止用户改变DataGridView1所有行的行高  
            gridWindows.AllowUserToResizeRows = false;

            // 禁止用户改变列头的高度  
            gridWindows.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;

            //不显示最左侧光标列
            gridHideWindow.RowHeadersVisible = false;
            //禁止用户改变DataGridView1所有行的行高  
            gridHideWindow.AllowUserToResizeRows = false;

            // 禁止用户改变列头的高度  
            gridHideWindow.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;

            //读取配置文件
            string _sv = FileHelper.ReadFileInfo(FileHelper.GetProcDir() + @"\ConfigInfo");
            if (!string.IsNullOrWhiteSpace(_sv))
            {
                if (!string.IsNullOrWhiteSpace(_sv))
                {
                    Config = JsonHelper.GetObjectFromJsonStr<ConfigModel>(_sv);
                }
            }
            chboxAutoRun.Checked = Config.IsAutoRun;
        }

        /// <summary>
        /// 确定保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            foreach (WinProc _wp in Common.IconProc)
            {
                if (Common.HideIconProcPath == null)
                {
                    Common.HideIconProcPath = new System.Collections.Generic.List<string>();
                }
                if (_wp.isHide)
                {
                    if (!Common.HideIconProcPath.Contains(_wp.lpProcImagePath))
                    {
                        Common.HideIconProcPath.Add(_wp.lpProcImagePath);
                    }

                    WindowIconHide.HideTrayIcon(_wp.idCommand, false);
                }
                else
                {
                    if (Common.HideIconProcPath.Contains(_wp.lpProcImagePath))
                    {
                        Common.HideIconProcPath.Remove(_wp.lpProcImagePath);
                    }

                    WindowIconHide.HideTrayIcon(_wp.idCommand, true);
                }
            }

            Common.HideWindowConfig.HideAllHotKey = txtAllHideHotKey.Text;

            FileHelper.SaveFileInfo(FileHelper.GetProcDir() + @"\HideIcon", JsonHelper.GetJsonStrFromObject(Common.HideIconProcPath));

            FileHelper.SaveFileInfo(FileHelper.GetProcDir() + @"\HideWindow", JsonHelper.GetJsonStrFromObject(Common.HideWindowConfig));


            //读取配置文件
            string _sv = FileHelper.ReadFileInfo(FileHelper.GetProcDir() + @"\ConfigInfo");
            if (!string.IsNullOrWhiteSpace(_sv))
            {
                if (!string.IsNullOrWhiteSpace(_sv))
                {
                    Config = JsonHelper.GetObjectFromJsonStr<ConfigModel>(_sv);
                }
            }
            if (Config == null)
            {
                Config = new ConfigModel();
                Config.MouseMiddleOpen = true;
                Config.OpenOnMouseXY = true;
            }
            if (chboxAutoRun.Checked)
            {
                SystemHelper.SetMeAutoStart(true);
            }
            else
            {
                SystemHelper.SetMeAutoStart(false);
            }

            Config.IsAutoRun = chboxAutoRun.Checked;

            FileHelper.SaveFileInfo(FileHelper.GetProcDir() + @"\ConfigInfo", JsonHelper.GetJsonStrFromObject(Config));

            DialogResult = DialogResult.OK;



        }

        /// <summary>
        /// 点击图标表格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridIcon_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (gridIcon.Columns[e.ColumnIndex].Name == "colisHide")
            {
                if (gridIcon.Rows[e.RowIndex].Cells["colisHide"].Value.ToString().ToLower() == "false")
                {
                    WinProc _wp = Common.IconProc.Find(m => m.id == Convert.ToInt32(gridIcon.Rows[e.RowIndex].Cells["colID"].Value));
                    if (_wp != null)
                    {
                        gridIcon.Rows[e.RowIndex].Cells["colisHide"].Value = true;
                        _wp.isHide = true;

                    }
                }
                else
                {
                    WinProc _wp = Common.IconProc.Find(m => m.id == Convert.ToInt32(gridIcon.Rows[e.RowIndex].Cells["colID"].Value));
                    if (_wp != null)
                    {
                        gridIcon.Rows[e.RowIndex].Cells["colisHide"].Value = false;
                        _wp.isHide = false;

                    }
                }
            }
        }

        /// <summary>
        /// 使TabControl的文字竖向显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
        {
            //Rectangle tabArea = tabControl1.GetTabRect(e.Index);//主要是做个转换来获得TAB项的RECTANGELF
            RectangleF tabTextArea = (RectangleF)(tabControl1.GetTabRect(e.Index));
            tabTextArea.X = tabTextArea.X + 5;
            Graphics g = e.Graphics;
            StringFormat sf = new StringFormat();//封装文本布局信息
            sf.LineAlignment = StringAlignment.Center;
            sf.Alignment = StringAlignment.Near;
            Font font = this.tabControl1.Font;
            SolidBrush brush = new SolidBrush(Color.Black);//绘制边框的画笔
            g.DrawString(((TabControl)(sender)).TabPages[e.Index].Text, font, brush, tabTextArea, sf);
        }

        /// <summary>
        /// 取消设置隐藏窗体快捷键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnHidePnl_Click(object sender, EventArgs e)
        {
            pnlHideHotKey.Visible = false;
        }

        /// <summary>
        /// 保存设置隐藏窗体快捷
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddHideWindow_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtHideHotKey.Text))
            {
                MessageBox.Show("请设置快捷键");
                return;
            }
            if (Common.HideWindowConfig == null)
            {
                Common.HideWindowConfig = new HideWindowConfig();
            }
            if (Common.HideWindowConfig.HideWindowList == null)
            {
                Common.HideWindowConfig.HideWindowList = new List<HideWindowInfo>();
            }
            Common.HideWindowConfig.HideWindowList.Add(new HideWindowInfo { HideHotKey = txtHideHotKey.Text, ProcessName = lblProcessName.Text });

            InitWindows();

            txtAllHideHotKey.Text = _HideAllHotKey;

            gridWindows.DataSource = _WindowsInfoList;
            gridHideWindow.DataSource = new System.ComponentModel.BindingList<HideWindowInfo>(Common.HideWindowConfig.HideWindowList);


            pnlHideHotKey.Visible = false;

        }

        /// <summary>
        /// 点击添加隐藏窗体快捷键按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddHideWindowHotKey_Click(object sender, EventArgs e)
        {
            if (gridWindows.CurrentRow != null)
            {
                lblProcessName.Text = Convert.ToString(gridWindows.CurrentRow.Cells["colProcessName"].Value);
                pnlHideHotKey.Visible = true;
                txtHideHotKey.Text = "";
                txtHideHotKey.Focus();
            }

        }

        /// <summary>
        /// 删除隐藏窗体快捷键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRemoveHideWindowHotKey_Click(object sender, EventArgs e)
        {
            if (gridHideWindow.CurrentRow != null)
            {
                string _processName = Convert.ToString(gridHideWindow.CurrentRow.Cells["colProcessName2"].Value);
                foreach (HideWindowInfo _hi in Common.HideWindowConfig.HideWindowList)
                {
                    if (_hi.ProcessName == _processName)
                    {
                        Common.HideWindowConfig.HideWindowList.Remove(_hi);
                        break;
                    }
                }

                InitWindows();

                txtAllHideHotKey.Text = _HideAllHotKey;

                gridWindows.DataSource = _WindowsInfoList;
                gridHideWindow.DataSource = new System.ComponentModel.BindingList<HideWindowInfo>(Common.HideWindowConfig.HideWindowList);
                if (gridHideWindow.RowCount > 0)
                {
                    gridHideWindow.Focus();
                }

            }
        }

        private void pnlHideHotKey_Paint(object sender, PaintEventArgs e)
        {

        }

        private void gridHideWindow_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }
    }
}
